package com.duowei.dw_pos;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.duowei.dw_pos.fragment.UpdateFragment;
import com.duowei.dw_pos.httputils.DownHTTP;
import com.duowei.dw_pos.httputils.VolleyResultListener;
import com.duowei.dw_pos.tools.CartList;
import com.duowei.dw_pos.tools.DataLoad;
import com.duowei.dw_pos.tools.Net;
import com.duowei.dw_pos.tools.PermissionsUtil;
import com.duowei.dw_pos.tools.Users;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SettingsActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.et_ip)
    EditText mEtIp;
    @BindView(R.id.et_port)
    EditText mEtPort;
    @BindView(R.id.et_pad)
    EditText mEtPad;
    @BindView(R.id.tv5)
    TextView mTv5;
    @BindView(R.id.checkbox)
    CheckBox mCheckbox;
    @BindView(R.id.rl_autoStart)
    RelativeLayout mRlAutoStart;
    @BindView(R.id.btn_load)
    Button mBtnLoad;
    @BindView(R.id.btn_back)
    Button mBtnBack;
    @BindView(R.id.cb_clear)
    CheckBox mCbClear;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    @BindView(R.id.cb_canSale)
    CheckBox mCbCanSale;
    @BindView(R.id.cb_doubleprint)
    CheckBox mCbDoubleprint;

    private SharedPreferences.Editor mEdit;
    private SharedPreferences mSp;
    private String mIp;
    private String mPad;
    private boolean auto;
    private boolean clear;
    private final String updateUrl = "http://androidwww.wxdw.top:2233/androidauth/app/dw_pos.txt";
    private boolean mCanSale;
    private boolean mDoubleprint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        PermissionsUtil.requestPermissions(this,PermissionsUtil.allPermissions);
        mSp = getSharedPreferences("user", Context.MODE_PRIVATE);
        mEdit = mSp.edit();
        initUI();
    }

    private void initUI() {
        mEtIp.setText(mSp.getString("ip", ""));
        mEtPad.setText(mSp.getString("pad", ""));
        auto = mSp.getBoolean("auto", true);
        clear = mSp.getBoolean("clear", false);
        mCanSale = mSp.getBoolean("canSale", false);
        mDoubleprint = mSp.getBoolean("doubleprint", false);
        mCheckbox.setChecked(auto);
        mCbClear.setChecked(clear);
        mCbCanSale.setChecked(mCanSale);
        mCbDoubleprint.setChecked(mDoubleprint);
        RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
        RadioButton rb1 = (RadioButton) findViewById(R.id.rb1);
        RadioButton rb2 = (RadioButton) findViewById(R.id.rb2);
        RadioGroup rg2 = (RadioGroup) findViewById(R.id.radioGroup2);
        RadioButton rb3 = (RadioButton) findViewById(R.id.rb3);
        RadioButton rb4 = (RadioButton) findViewById(R.id.rb4);
        RadioGroup rg3 = (RadioGroup) findViewById(R.id.radioGroup3);
        RadioButton rb5 = (RadioButton) findViewById(R.id.rb5);
        RadioButton rb6 = (RadioButton) findViewById(R.id.rb6);
        String orderstytle = mSp.getString("orderstytle", getResources().getString(R.string.order_stytle_zhongxican));
        String cashpay = mSp.getString("cashpay", getString(R.string.cash_unallowed));
        String rounding = mSp.getString("rounding", getResources().getString(R.string.rounding_jiao));
        if (orderstytle.equals(getResources().getString(R.string.order_stytle_zhongxican))) {
            rb1.setChecked(true);
        } else if (orderstytle.equals(getResources().getString(R.string.order_stytle_kuaican))) {
            rb2.setChecked(true);
        }
        if (cashpay.equals(getString(R.string.cash_allow))) {
            rb4.setChecked(true);
        } else if (cashpay.equals(getString(R.string.cash_unallowed))) {
            rb3.setChecked(true);
        }
        if (rounding.equals(getString(R.string.rounding_jiao))) {
            rb5.setChecked(true);
        } else if (rounding.equals(getString(R.string.rounding_yuan))) {
            rb6.setChecked(true);
        }
        mTvVersion.setText(LandActivity.mVersionName);
        checkPermission();
        rg.setOnCheckedChangeListener(this);
        rg2.setOnCheckedChangeListener(this);
        rg3.setOnCheckedChangeListener(this);
    }
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private void checkPermission() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }
    @OnClick({R.id.rl_clearData, R.id.rl_autoStart, R.id.btn_load, R.id.btn_back, R.id.rl_version,
            R.id.rl_saleNum,R.id.rl_doublePrint})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_clearData:
                clear = !clear;
                mCbClear.setChecked(clear);
                mEdit.putBoolean("clear", clear);
                mEdit.commit();
                break;
            case R.id.rl_autoStart:
                auto = !auto;
                mCheckbox.setChecked(auto);
                mEdit.putBoolean("auto", auto);
                mEdit.commit();
                break;
            case R.id.rl_saleNum:
                mCanSale = !mCanSale;
                mCbCanSale.setChecked(mCanSale);
                mEdit.putBoolean("canSale", mCanSale);
                mEdit.commit();
                break;
            case R.id.rl_doublePrint:
                mDoubleprint=!mDoubleprint;
                mCbDoubleprint.setChecked(mDoubleprint);
                mEdit.putBoolean("doubleprint",mDoubleprint);
                mEdit.commit();
                break;
            case R.id.rl_version:
                checkVersion();
                break;
            case R.id.btn_load:
                mIp = mEtIp.getText().toString().trim();
                mPad = mEtPad.getText().toString().trim();
                if (TextUtils.isEmpty(mIp)) {
                    Toast.makeText(this, "请填写IP地址", Toast.LENGTH_SHORT).show();

                } else if (TextUtils.isEmpty(mPad)) {
                    Toast.makeText(this, "请设置手持POS名称", Toast.LENGTH_SHORT).show();

                } else {
                    Net.url = "http://" + mIp + ":2233/server/ServerSvlt?";
                    Users.pad = mPad;
                    mEdit.putString("ip", mIp);
                    mEdit.putString("pad", mPad);
                    mEdit.putString("url", Net.url);
                    mEdit.commit();
                    DataLoad.getInstance().startLoad(this);
                }
                break;
            case R.id.btn_back:
                finish();
                break;
        }
    }

    private void checkVersion() {
        DownHTTP.getVolley(updateUrl, new VolleyResultListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String versionCode = jsonObject.getString("versionCode");
                    if (Integer.parseInt(versionCode) > LandActivity.mVersionCode) {
                        final String name = jsonObject.getString("name");
                        final String url = jsonObject.getString("url");
                        String msg = jsonObject.getString("msg");
                        showDialog(name, url, msg);
                    } else {
                        Toast.makeText(SettingsActivity.this, "当前己是最新版", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showDialog(final String name, final String url, String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
        builder.setIcon(R.mipmap.logo);
        builder.setTitle("发现新版本是否升级？");
        builder.setMessage(msg);
        builder.setNegativeButton("暂不升级", null);
        builder.setPositiveButton("立即升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                UpdateFragment fragment = UpdateFragment.newInstance(url, name);
                fragment.show(getFragmentManager(), getString(R.string.update));
            }
        });
        builder.show();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
        int radioButtonId = radioGroup.getCheckedRadioButtonId();
        RadioButton rb = (RadioButton) findViewById(radioButtonId);
        if (radioGroup.getId() == R.id.radioGroup) {
            mEdit.putString("orderstytle", rb.getText().toString());
        } else if (radioGroup.getId() == R.id.radioGroup2) {
            mEdit.putString("cashpay", rb.getText().toString());
        } else if (radioGroup.getId() == R.id.radioGroup3) {
            mEdit.putString("rounding", rb.getText().toString());
        }
        mEdit.commit();
        CartList.newInstance(this).clear();
    }
}
